package cn.gzjp.modules.woms.web.front;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import cn.gzjp.common.constant.Constants;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.modules.sys.utils.DictUtils;
import cn.gzjp.modules.woms.entity.EventPic;
import cn.gzjp.modules.woms.entity.EventProcess;
import cn.gzjp.modules.woms.service.EventPicService;
import cn.gzjp.modules.woms.service.EventProcessService;
import cn.hutool.core.util.ImageUtil;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.cp.api.WxCpService;

import org.apache.commons.io.FilenameUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import cn.gzjp.common.constant.Constants.*;


import cn.gzjp.common.config.Global;
import cn.gzjp.common.utils.FileUtils;
import cn.gzjp.common.web.AjaxResult;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.woms.entity.Event;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.EventService;
import cn.gzjp.modules.woms.service.WorkerService;
import cn.gzjp.modules.wx.service.QyWxService;

/**
 * 企业号--故障处理应用（外场运维人员）
 */
@Controller
@RequestMapping(value = "${frontPath}/engineer")
@SessionAttributes(value = {"corpId", "userId"})
public class EngineerController extends BaseController {

    @Autowired
    private EventService eventService;
    @Autowired
    private QyWxService qyWxService;
    @Autowired
    private WorkerService workerService;


    /**
     * 未处理列表展示(未处理菜单)
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("undo")
    public String undo(@ModelAttribute("userId") String userId, Model model) {
        Event event = new Event();
        event.setEnginnerId(userId);
        event.setEngineerUndo("y");
        //自己组装查询条件
        List<Event> eventList = eventService.findList(event);
        Collections.sort(eventList, new Comparator<Event>(){
            public int compare(Event o1, Event o2) {
                if(o1.getLeftMinutes() > o2.getLeftMinutes()){
                    return 1;
                }
                if(o1.getLeftMinutes() == o2.getLeftMinutes()){
                    return 0;
                }
                return -1;
            }
        });
        model.addAttribute("eventList", eventList);
        return "modules/woms/front/engineer/undoList";
    }


    /**
     * 处理中工单列表(处理中菜单)
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("doing")
    public String doing(@ModelAttribute("userId") String userId, Model model) {
        Event event = new Event();
        event.setEnginnerId(userId);
        event.setEngineerDoing("y");
        List<Event> eventList = eventService.findList(event);
        Collections.sort(eventList, new Comparator<Event>(){
            public int compare(Event o1, Event o2) {
                if(o1.getLeftMinutes() > o2.getLeftMinutes()){
                    return 1;
                }
                if(o1.getLeftMinutes() == o2.getLeftMinutes()){
                    return 0;
                }
                return -1;
            }
        });
        model.addAttribute("eventList", eventList);
        return "modules/woms/front/engineer/doingList";
    }

    /**
     * 已处理工单列表(已处理菜单)
     *
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping("done")
    public String done(@ModelAttribute("userId") String userId, Model model) {
        Event event = new Event();
        event.setEnginnerId(userId);
        event.setEngineerDone("y");
        List<Event> eventList = eventService.findList(event);
        model.addAttribute("eventList", eventList);
        Collections.sort(eventList, new Comparator<Event>(){
            public int compare(Event o1, Event o2) {
                if(o1.getLeftMinutes() > o2.getLeftMinutes()){
                    return 1;
                }
                if(o1.getLeftMinutes() == o2.getLeftMinutes()){
                    return 0;
                }
                return -1;
            }
        });
        return "modules/woms/front/engineer/doneList";
    }

    /**
     * 详细展示
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "event", method = RequestMethod.GET)
    public String event(String id, Model model) {
        Event event = eventService.get(id);
        model.addAttribute("event", event);
        return "modules/woms/front/engineer/event";
    }
    /**
     * 详细展示
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "event2", method = RequestMethod.GET)
    public String event2(String id, Model model) {
        Event event = eventService.get(id);
        model.addAttribute("event", event);
        return "modules/woms/front/engineer/event2";
    }

    /**
     * 点击接收进到接收工单页面
     * @param id 工单id
     * @param model
     * @return
     */
    @RequestMapping(value = "receiveUI")
    public String receiveUI(String id, Model model) {
        Event event = eventService.get(id);
        model.addAttribute("event", event);
        //如果不是分派状态,无需接收,有可能被其他2货接收了
        if(!EventStatus.assign.equals(event.getStatus())){
            return "modules/woms/front/engineer/event";
        }
        return "modules/woms/front/engineer/receive";

    }

    /**
     * 点击确认接收工单
     * @param userId 工作人员id
     * @param id   工单id
     * @param zrgsType 责任归属
     * @param zrgsDesc 责任归属描述
     * @param faultType 故障类型
     * @param faultDesc 故障描述
     * @param lwpqType 劳务派遣类型
     * @param lwpqDesc 劳务派遣描述
     * @param zrgsPics 责任归属图片
     * @param lwpqDesc 故障描述图片
     * @param lwpqDesc 劳务派遣图片
     * @return
     */
    @RequestMapping(value = "receive", method = RequestMethod.POST)
    @ResponseBody
    public String receive(@ModelAttribute("userId") String userId,String id,String zrgsType,
                          String zrgsDesc,String faultType,String faultDesc,String lwpqType,
                          String lwpqDesc,
                          String[] zrgsPics,
                          String[] faultPics,
                          String[] lwpqPics) {
        Event event = eventService.get(id);
        Worker worker = workerService.get(userId);
        if(!EventStatus.assign.equals(event.getStatus())){
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("该工单已接收,无需重复接收");
            return this.mapper.toJson(ajaxResult);
        }

        event.setStatus(EventStatus.receive);
        event.setReceiverId(userId);
        event.setReceiveTime(new Date());
        event.setZrgsDesc(zrgsDesc);
        event.setZrgsType(zrgsType);
        event.setFaultType(faultType);
        event.setFaultDesc(faultDesc);
        event.setLwpqType(lwpqType);
        event.setLwpqDesc(lwpqDesc);
        eventService.receive(event,userId,zrgsPics,faultPics,lwpqPics);
        //推送消息 推送给分派员
        sendQyWxMessage(event, AgentId.assigner,"工单已被工程师接收","您分派的工单已被工程师"+worker.getName()+"接收",event.getAssigner().getId());
        //推送给自己
        sendQyWxMessage(event, AgentId.enginer,"工单接收成功","你成功接收工单，尽快去处理吧",worker.getId());
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        ajaxResult.setMsg("工单接收成功");
        return this.mapper.toJson(ajaxResult);

    }


    /**
     * 故障处理(故障回复页面)
     * @param id 工单id
     * @param model
     * @return
     */
    @RequestMapping(value = "processUI")
    public String processUI(String id, Model model) {
        Event event = eventService.get(id);
        model.addAttribute("event", event);
        return "modules/woms/front/engineer/process";

    }

    /**
     * 故障处理(故障回复提交)
     * @param id
     * @param status  4处理工单,5完成
     * @param content 回复内容
     * @param pics 已上传的图片路径数组
     * @return
     */
    @RequestMapping(value = "process", method = RequestMethod.POST)
    @ResponseBody
    public String process(@ModelAttribute("userId") String userId,String id,String status,String content,String[] pics) {
        Event event = eventService.get(id);
        Worker worker = workerService.get(userId);
        event.setStatus(status);
        eventService.process(event,userId,content,pics);
        if(status.equals(EventStatus.process)){
            //推送消息 推送给分派员
            sendQyWxMessage(event, AgentId.assigner,"工单工程师已回复处理","您分派的工单已被工程师"+worker.getName()+"回复处理",event.getAssigner().getId());
        }
        if(status.equals(EventStatus.complete)){
            //推送消息 推送给分派员
            sendQyWxMessage(event, AgentId.assigner,"工单工程师已处理完成","您分派的工单已被工程师"+worker.getName()+"回复处理完成",event.getAssigner().getId());
            //推送给内场运维人员
            sendQyWxMessage(event, Constants.AgentId.achieve,"你有工单需要核实确认","您提交的工单已被工程师"+worker.getName()+"回复处理完成,请尽快核实确认",event.getCreaterId());
        }
        //推送给工程师自己
        sendQyWxMessage(event, AgentId.enginer,"工单处理提交成功","你成功回复了设备"+event.getDeviceName()+"故障信息",userId);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(true);
        ajaxResult.setMsg("工单处理操作成功");
        return this.mapper.toJson(ajaxResult);
    }



    /**
     * 图片上传
     * @param corpId
     * @param userId
     * @param mediaId
     * @return
     */
    @RequestMapping(value = "uploadPic")
    @ResponseBody
    public String uploadPic(@ModelAttribute("corpId") String corpId,
                            @ModelAttribute("userId") String userId, String mediaId,
                            HttpServletRequest request) {
        AjaxResult result = new AjaxResult(true, "操作成功！");
        try {
            WxCpService wxCpService = this.qyWxService.getWxCpService(corpId,
                    AgentId.enginer);
            File srcFile = wxCpService.mediaDownload(mediaId);
            String extension = FilenameUtils.getExtension(srcFile.getName());
            // 文件保存路径
            String realPath = Global.USERFILES_BASE_URL + "/file/";
            // 转存文件
            FileUtils.createDirectory(Global.getUserfilesBaseDir() + realPath);
            String destFileName = mediaId + "." + extension;
            File destFile = new File(Global.getUserfilesBaseDir() + realPath + destFileName);
            FileUtil.copyFile(srcFile, destFile);
            String destFileNameScale = mediaId + "_s." + extension;
            File destFileScale = new File(Global.getUserfilesBaseDir() + realPath + destFileNameScale);
            ImageUtil.scale(destFile,destFileScale,0.3f);//压缩
            String img = request.getContextPath() + realPath + destFileNameScale;
            result.setSuccess(true);
            result.setMsg(img);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(true);
            result.setMsg("失败");
        }
        return this.mapper.toJson(result);
    }

    /**
     * 用于页面js授权
     * @param corpId
     * @param url
     * @return
     */
    @RequestMapping(value = "jsApi", method = RequestMethod.POST)
    @ResponseBody
    public String jsApi(@ModelAttribute(value = "corpId") String corpId,
                        @RequestParam("url") String url) {
        AjaxResult ajaxResult = new AjaxResult();
        WxJsapiSignature jspTitck;
        try {
            WxCpService wxCpService = this.qyWxService.getWxCpService(corpId,
                    AgentId.enginer);
            jspTitck = wxCpService.createJsapiSignature(url);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("timestamp", jspTitck.getTimestamp());
            map.put("nonceStr", jspTitck.getNoncestr());
            map.put("signature", jspTitck.getSignature());
            ajaxResult.setSuccess(true);
            String json = mapper.toJson(map);
            ajaxResult.setMsg(json);
        } catch (Exception e) {
            ajaxResult.setSuccess(false);
        }
        return mapper.toJson(ajaxResult);
    }


}
